package com.gbco.intelligentpush.async;

import com.alibaba.fastjson.JSONObject;
import com.gbco.intelligentpush.utils.JedisAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EventConsumer implements InitializingBean , ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Autowired
    private JedisAdapter jedisAdapter;

    private Map<EventType, List<EventHandler>> handlerMap = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {

        log.info("consumer:Initializing...");

        Map<String, EventHandler> maps = applicationContext.getBeansOfType(EventHandler.class);
        if(maps!=null){

            for (EventHandler eventHandler : maps.values()){
                List<EventType> eventTypes = eventHandler.getSurpportEventType();
                for (EventType eventType : eventTypes) {
                    if(!maps.containsKey(eventType)){
                        handlerMap.put(eventType,new ArrayList<>());
                    }
                    handlerMap.get(eventType).add(eventHandler);
                }
            }
        }

        log.info("consumer:加载完毕...");

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                String message ;
                EventType eventType ;
                while(true){
                    message = jedisAdapter.brpop("async").get(1);
                    EventModel eventModel = JSONObject.parseObject(message, EventModel.class);
                    eventType = eventModel.getEventType();
                    log.info(eventType+"");
                    if(!handlerMap.containsKey(eventType)){
                        log.info("不能解决的事件");
                        continue;
                    }
                    for (EventHandler eventHandler : handlerMap.get(eventType)){
                        eventHandler.deal(eventModel);
                    }
                }
            }
        });
        thread.start();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
